package com.hg.chapter4.onverters;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Base64;

public class MyMessageConverters extends AbstractHttpMessageConverter<Man> {
    //表明置处理man类
    @Override
    protected boolean supports(Class<?> aClass) {
        return Man.class.isAssignableFrom(aClass);
    }

    //修改request
    @Override
    protected Man readInternal(Class<? extends Man> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        System.out.println(httpInputMessage.getBody());
        String[] result = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8")).split("-");
        return new Man(result[0], result[1]);
    }

    //修改response
    @Override
    protected void writeInternal(Man man, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        httpOutputMessage.getBody().write(man.toString().getBytes());
    }
}
